const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const urlLib = require('url');

var server = http.Server(function (req,res) {
	var POSTData;
	// GET
	var obj = urlLib.parse(req.url,true);
	var url = obj.pathname;
	const GETdata = obj.query;
	// POST
	var strData = '';
	req.on('data',function (data) {
		strData += data;
	});
	req.on('end',function () {
		POSTData = querystring.parse(strData);
	});

	// 文件请求(路由)
	var page404 = fs.readFileSync('./www/404.html');
	var file_name = './www' + url;
	if (url === '/')  file_name = './www/index.html';
	fs.readFile(file_name, function (err,data) {
		if (err) res.write(page404); 
		else res.write(data); 
		res.end();
	});

	var retData = {
		urlPath : url,
		Pdata : POSTData,
		Gdata : GETdata 
	}
	console.log(retData);
});

server.listen(3000);
console.log('跑起来了');